package MyTest01.service.impl;

import MyTest01.bean.Goods;
import MyTest01.bean.Sale;
import MyTest01.dao.GoodsDao;
import MyTest01.dao.SaleDao;
import MyTest01.exception.NotEnoughException;
import MyTest01.service.BuyGoodsService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author HLF
 * @version V1.0
 * @package MyTest01.service.impl
 * @date 2021/10/24 9:54
 */
public class BuyGoodsServiceImpl implements BuyGoodsService {
    private GoodsDao goodsDao;
    private SaleDao saleDao;

    @Transactional(
            propagation = Propagation.REQUIRED,
            isolation = Isolation.REPEATABLE_READ,
            readOnly = false,
            rollbackFor = {
                    NullPointerException.class, NotEnoughException.class
            }
    )
    @Override
    public void buy(Integer goodId, Integer nums) {
        System.out.println("====buy方法开始====");

        //1.增加销售记录
        Sale sale = new Sale(null, goodId, nums);
        saleDao.insertSale(sale);

        //2.更新商品余量库存
        Goods goods = goodsDao.selectGoodsById(goodId);
        if (goods == null) {
            throw new NullPointerException("商品不存在！");
        } else if (nums > goods.getAmount()) {
            throw new NotEnoughException("商品余量不足！");
        } else {
            int i = goodsDao.updateGoods(new Goods(goodId, null, nums, null));

            System.out.println("====buy方法结束====");
        }
    }

    public void setSaleDao(SaleDao saleDao) {
        this.saleDao = saleDao;
    }

    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }
}
